package com.wsoft.im.service.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wsoft.core.exception.Asserts;
import com.wsoft.core.utils.LoginUserUtil;
import com.wsoft.im.entity.ImGroupEntity;
import com.wsoft.im.entity.ImGroupMemberEntity;
import com.wsoft.im.manager.ImGroupManager;
import com.wsoft.im.manager.ImGroupMemberManager;
import com.wsoft.im.mapper.ImGroupMapper;
import com.wsoft.im.query.group.AddGroupQuery;
import com.wsoft.im.query.group.UpdateGroupQuery;
import com.wsoft.im.service.IImGroupService;
import com.wsoft.im.util.GroupMemberUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 群组 服务实现类
 * </p>
 *
 * @author Z001
 * @since 2025年01月14日 09:21:07
 */
@Service
public class ImGroupServiceImpl extends ServiceImpl<ImGroupMapper, ImGroupEntity> implements IImGroupService {

    @Resource
    private ImGroupManager groupManager;
    @Resource
    private ImGroupMemberManager groupMemberManager;

    /**
     * 群成员最小个数,不包含群组
     */
    private static final int GROUP_MIN_SIZE = 2;


    /**
     * 新增群组
     * @param query
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertGroup(AddGroupQuery query) {
        List<Long> memberIdList = query.getMemberIdList();
        memberIdList.remove(LoginUserUtil.getUserInfo().getLoginUserVO().getId());
        if( memberIdList.size() < GROUP_MIN_SIZE){
            //建群人数需大于3
            Asserts.fail("[im.group.min.member.error]");
        }
        ImGroupEntity groupEntity = Convert.convert(ImGroupEntity.class, query);
        boolean b = groupManager.save(groupEntity);
        if(b){
            Long groupId = groupEntity.getId();
            List<ImGroupMemberEntity> groupMemberList = GroupMemberUtil.buildGroupMember(groupId, query.getMemberIdList(),true);
            groupMemberManager.saveBatch(groupMemberList);
        }
        return b;
    }

    /**
     * 修改群组信息
     * @param query
     * @return
     */
    @Override
    public boolean updateGroup(UpdateGroupQuery query) {
        ImGroupEntity convert = Convert.convert(ImGroupEntity.class, query);
        return groupManager.updateById(convert);
    }

    /**
     * 根据id获取
     * @param id
     * @return
     */
    @Override
    public ImGroupEntity getGroupInfo(Long id) {
        return groupManager.getById(id);
    }


    // ################################## 私有方法  ##################################


}
